package com.xydtech.ecard.merchant.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.annotation.Log;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.page.TableDataInfo;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.merchant.domain.EcardAgricultureInfo;
import com.xydtech.ecard.merchant.domain.EcardMerchantPartInfo;
import com.xydtech.ecard.merchant.domain.EcardReleaseRecord;
import com.xydtech.ecard.merchant.service.IEcardAgricultureInfoService;
import com.xydtech.ecard.merchant.service.IEcardMerchantPartInfoService;
import com.xydtech.ecard.merchant.service.IEcardReleaseRecordService;
import com.xydtech.ecard.merchant.utils.MyExcelUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子名片新型农业主体信息Controller
 *
 * @author yuzhiguo
 * @date 2024-08-21 下午4:23
 */
@Controller
@RequestMapping("/merchant/agriculture")
public class EcardAgricultureInfoController extends BaseController
{
    private String prefix = "merchant";

    @Autowired
    private IEcardAgricultureInfoService ecardAgricultureInfoService;
    @Autowired
    private IEcardReleaseRecordService ecardReleaseRecordService;
    @Autowired
    private IEcardMerchantPartInfoService ecardMerchantPartInfoService;

    @RequiresPermissions("merchant:agriculture:view")
    @GetMapping()
    public String agriculture()
    {
        return prefix + "/agriculture";
    }

    //跳转新型农业主体天眼查更多信息
    @RequiresPermissions("merchant:agriculture:view")
    @GetMapping("/agricultureTyc/{id}")
    public String moreInfo(@PathVariable("id") String id, ModelMap mmap)
    {
        String salt = getSalt();//盐值
        EcardAgricultureInfo ecardAgricultureInfo = ecardAgricultureInfoService.selectEcardAgricultureInfoById(Long.valueOf(id), salt);
        mmap.put("ecardAgricultureInfo", ecardAgricultureInfo);
        return prefix + "/agricultureTyc";
    }

    /**
     * 查询电子名片新型农业主体信息列表
     */
    @RequiresPermissions("merchant:agriculture:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(EcardAgricultureInfo ecardAgricultureInfo)
    {
        String salt = getSalt();//盐值
        startPage();
        List<EcardAgricultureInfo> list = ecardAgricultureInfoService.selectEcardAgricultureInfoList(ecardAgricultureInfo, salt);
        return getDataTable(list);
    }

    /**
     * 导出电子名片新型农业主体信息列表
     */
    @RequiresPermissions("merchant:agriculture:export")
    @GetMapping("/export/{dataParam}")
    @ResponseBody
    public void export(@PathVariable("dataParam") String dataParam, HttpServletResponse response)
    {
        String salt = getSalt();//盐值
        //处理查询条件
        EcardAgricultureInfo ecardAgricultureInfo = new EcardAgricultureInfo();
        JSONArray parsed = (JSONArray) JSONObject.parse(dataParam);
        String ids = "";
        Map<String, Object> paramMap = new HashMap<>();
        for (Object o : parsed) {
            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(o));
            if ("params[startDate]".equals(jsonObject.getString("name"))){
                paramMap.put("startDate",jsonObject.getString("value"));
            } else if ("params[endDate]".equals(jsonObject.getString("name"))){
                paramMap.put("endDate",jsonObject.getString("value"));
            } else if ("deptId".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setDeptId(jsonObject.getLong("value"));
            } else if ("userName".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setUserName(jsonObject.getString("value"));
            } else if ("agrCustName".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setAgrCustName(jsonObject.getString("value"));
            } else if ("agrType".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setAgrType(jsonObject.getInteger("value"));
            } else if ("sortTime".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setSortTime(jsonObject.getString("value"));
            } else if ("releaseSts".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setReleaseSts(jsonObject.getString("value"));
            } else if ("visitSts".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setVisitSts(jsonObject.getString("value"));
            } else if ("tycsts".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setTycsts(jsonObject.getString("value"));
            } else if ("state".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setState(jsonObject.getInteger("value"));
            } else if ("ids".equals(jsonObject.getString("name"))){
                ids = jsonObject.getString("value");
            } else if ("id".equals(jsonObject.getString("name"))){
                ecardAgricultureInfo.setId(jsonObject.getLong("value"));
            }
        }
        ecardAgricultureInfo.setParams(paramMap);//时间条件
        List<EcardAgricultureInfo> list = new ArrayList<>();
        if (ecardAgricultureInfo.getDeptId() == null){
            ecardAgricultureInfo.setDeptId(ShiroUtils.getSysUser().getDeptId());
        }
        //判断ids是否为空，不为空则导出选择的数据
        if (StringUtils.objIsNullOrEmpty(ids)){
            list = ecardAgricultureInfoService.selectEcardAgricultureInfoListByExport(ecardAgricultureInfo, salt);
        } else {
            ids = ids.replaceAll("\\[","").replaceAll("]","");
            list = ecardAgricultureInfoService.selectEcardAgricultureInfoByIds(ids, salt);
        }
        for (EcardAgricultureInfo agricultureInfo : list) {
            //查询新型农业主体成员信息
            EcardMerchantPartInfo merchantPartInfo = new EcardMerchantPartInfo();
            merchantPartInfo.setMerchantId(agricultureInfo.getId());
            merchantPartInfo.setMerchantType("4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            List<EcardMerchantPartInfo> partInfoList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoListByExport(merchantPartInfo, salt);
            agricultureInfo.setMerchantPartDetail(partInfoList);
        }
        MyExcelUtils.exportExcel(list,
                "电子名片新型农业主体信息",
                "电子名片新型农业主体",
                EcardAgricultureInfo.class,
                "电子名片新型农业主体信息文件" + System.currentTimeMillis() + ".xls", response);
    }

    /**
     * 选择转交的客户经理
     */
    @RequiresPermissions("merchant:agriculture:handOver")
    @GetMapping("/handOver/{ids}")
    public String choiceUserByHand(@PathVariable("ids") String ids, ModelMap mmap) {
        mmap.put("ids", ids);
        mmap.put("merchantType", "4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
        return prefix + "/choiceUser";
    }

    /**
     * 新型农业主体信息转交
     */
    @Log(title = "新型农业主体信息转交客户经理", businessType = BusinessType.UPDATE)
    @PostMapping("/allocation")
    @ResponseBody
    public AjaxResult allocation(Long registId,Long deptId, Long[] ids, Long userId) {
        /**查询机构*/
        //SysUser user = sysUserService.selectUserById(userId);
        if(registId == null){
            return AjaxResult.error("请选择移交人员！");
        }
        if(deptId == null){
            return AjaxResult.error("请选择移交的机构！");
        }

        //移交新型农业主体信息列表
        List<EcardAgricultureInfo> ecardAgricultureInfoList = new ArrayList<>();

        for (int i = 0; i < ids.length; i++) {
            //修改管户人id和创建人机构id
            EcardAgricultureInfo ecardAgricultureInfo = new EcardAgricultureInfo();
            ecardAgricultureInfo.setId(ids[i]);
            ecardAgricultureInfo.setManagementPersonnelId(registId);
            ecardAgricultureInfo.setDeptId(deptId);
            ecardAgricultureInfoList.add(ecardAgricultureInfo);
        }

        return toAjax(ecardAgricultureInfoService.allocationEcardAgricultureInfo(ecardAgricultureInfoList,registId, userId));
    }

    /**
     * 释放新型农业主体
     *
     * @author yuzhiguo
     * @date 2024/8/22 上午8:58
     */
    @RequiresPermissions("merchant:agriculture:handOver")
    @Log(title = "释放新型农业主体", businessType = BusinessType.UPDATE)
    @PostMapping("/release")
    @ResponseBody
    public AjaxResult release(Long[] ids) {
        String salt = getSalt();//盐值
        //释放新型农业主体列表
        List<EcardAgricultureInfo> ecardAgricultureInfoList = new ArrayList<>();
        Long userId = ShiroUtils.getSysUser().getUserId();
        //新增新型农业主体释放记录
        List<EcardReleaseRecord> ecardReleaseRecordList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            //修改创建人id和创建人机构id
            EcardAgricultureInfo ecardAgricultureInfo = new EcardAgricultureInfo();
            ecardAgricultureInfo.setId(ids[i]);
            ecardAgricultureInfo.setManagementPersonnelId(null);
            ecardAgricultureInfoList.add(ecardAgricultureInfo);

            EcardAgricultureInfo agricultureInfo = ecardAgricultureInfoService.selectEcardAgricultureInfoById(ids[i], salt);//查询新型农业主体信息
            //新增释放记录
            EcardReleaseRecord ecardReleaseRecord = new EcardReleaseRecord();
            ecardReleaseRecord.setReleaseId(userId);//释放人用户id
            ecardReleaseRecord.setMerchantId(ids[i]);//新型农业主体id
            ecardReleaseRecord.setBelongRegistId(agricultureInfo.getManagementPersonnelId());//新型农业主体归属人注册id
            ecardReleaseRecord.setMerchantType("4");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            ecardReleaseRecordList.add(ecardReleaseRecord);
        }
        ecardReleaseRecordService.batchInsertEcardReleaseRecord(ecardReleaseRecordList);//批量新增释放记录
        int i = ecardAgricultureInfoService.batchReleaseEcardAgricultureInfo(ecardAgricultureInfoList);
        return toAjax(i);
    }

    /**
     * 启用/停用新型农业主体
     *
     * @author yuzhiguo
     * @date 2024/8/16 下午3:32
     */
    @RequiresPermissions("merchant:agriculture:switchOver")
    @Log(title = "启用/停用新型农业主体", businessType = BusinessType.UPDATE)
    @PostMapping("/switchOver")
    @ResponseBody
    public AjaxResult switchOver(Long[] ids, Integer state) {
        //新型农业主体列表
        List<EcardAgricultureInfo> ecardAgricultureInfoList = new ArrayList<>();

        for (int i = 0; i < ids.length; i++) {
            //修改创建人id和创建人机构id
            EcardAgricultureInfo ecardAgricultureInfo = new EcardAgricultureInfo();
            ecardAgricultureInfo.setId(ids[i]);
            ecardAgricultureInfo.setState(state);
            ecardAgricultureInfoList.add(ecardAgricultureInfo);
        }
        int i = ecardAgricultureInfoService.batchSwitchOverEcardAgricultureInfo(ecardAgricultureInfoList);
        return toAjax(i);
    }

    /**
     * 新增电子名片新型农业主体信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存电子名片新型农业主体信息
     */
    @RequiresPermissions("merchant:agriculture:add")
    @Log(title = "电子名片新型农业主体信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(EcardAgricultureInfo ecardAgricultureInfo)
    {
        String salt = getSalt();//盐值
        return toAjax(ecardAgricultureInfoService.insertEcardAgricultureInfo(ecardAgricultureInfo, salt));
    }

    /**
     * 修改电子名片新型农业主体信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        String salt = getSalt();//盐值
        EcardAgricultureInfo ecardAgricultureInfo = ecardAgricultureInfoService.selectEcardAgricultureInfoById(id, salt);
        mmap.put("ecardAgricultureInfo", ecardAgricultureInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存电子名片新型农业主体信息
     */
    @RequiresPermissions("merchant:agriculture:edit")
    @Log(title = "电子名片新型农业主体信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(EcardAgricultureInfo ecardAgricultureInfo)
    {
        String salt = getSalt();//盐值
        return toAjax(ecardAgricultureInfoService.updateEcardAgricultureInfo(ecardAgricultureInfo, salt));
    }

    /**
     * 删除电子名片新型农业主体信息
     */
    @RequiresPermissions("merchant:agriculture:remove")
    @Log(title = "电子名片新型农业主体信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ecardAgricultureInfoService.deleteEcardAgricultureInfoByIds(ids));
    }
}
